const { show, msg } = require('../game/alert');
const EventServices = require('../util/EventServices');
const { shopData, foodMaterials, foodList, time  } = require('./gameData')
const { prefabArray, PrefabCache, prefabPool, putPrefabPool, getPrefabPool } = require("../util/gameResources");
const { videoAds } = require('../ads/video');
// const { regeneratorRuntime } = require('regenerator-runtime');
cc.Class({
    extends: cc.Component,

    properties: {
       shopName:cc.Label,
       workers:cc.Label,
       customer:cc.Label,
       income:cc.Label,
       money:cc.Label,
       koubei:cc.Label,
       weatherImg:cc.Sprite,
       weather:cc.Label,
       famous:cc.Label,
       foodList:cc.Node,
       unlockList:cc.Node,
       foodPrefab:cc.Prefab,
       _curLoadIdx: 0,
       loadingFinish: false,
    },

    // LIFE-CYCLE CALLBACKS:

    
    
    onEnable () {
        console.log('显示了')
        cc.log(shopData);
        //获取店铺内容
        window.shop = shopData.shopList.find(val=>{
            return val.id == shopId;
        })
        // this.executePreFrame(this.lazyLoad(shop.menuList.length));
        // this.scheduleOnce(this.setFoodList,1);
        this.scheduleOnce(() => {
            if(shop.famous <= 10) {
                msg('店铺知名度有点低，建议多宣传宣传');
            }
        },3)
        if(shop.status == 1) {
            this.initShop();
        }else{
            EventServices.subscribe("fixShop", () => {
                this.initShop();
            })
            let item = cc.instantiate(PrefabCache['fixShop']);
            item.parent = this.node;
        }
        // this.scheduleOnce(() => {
        //     this.foodList.children.forEach(val=>{
        //         cc.log(val)
        //         putPrefabPool(val.name, val);
        //     })
        // },2)
    },
    initShop () {
        this.setData(shop);
        EventServices.subscribe('shopUpdate', (shopIndex, foodIndex) => {
            console.log('收到消息');
            if(shop.foodList && shop.foodList.length > 0) {
                this.foodList.children[foodIndex].getChildByName("sales").getComponent(cc.Label).string = `销量:${formatMoney(shop.foodList[foodIndex].sales)}`
                this.foodList.children[foodIndex].getChildByName("famous").getComponent(cc.Label).string = `库存:${formatMoney(shop.foodList[foodIndex].stock)}`
            }
           })
        EventServices.subscribe('unlockFood',(food, index) => {
                let item  = getPrefabPool('food');
                this.foodList.addChild(item);
                item.getChildByName("foodName").getComponent(cc.Label).string = `${food.name}`
                item.getChildByName("sales").getComponent(cc.Label).string = `销量:${formatMoney(food.sales)}`
                item.getChildByName("price").getComponent(cc.Label).string = `价格:${formatMoney(food.price)}`
                item.getChildByName("famous").getComponent(cc.Label).string = `库存:${formatMoney(food.stock)}`
                item.getChildByName("level").getComponent(cc.Label).string = `${(food.level)}级`
                item.getChildByName("levelCost").getComponent(cc.Label).string = `下级:${formatMoney(food.levelCost)}`;
                //合成表
                item.id = food.id;
                shop.foodList[index].state = 1;
                this.foodList.height += 110;
                // this.foodList.parent.height += 105;

        });
        EventServices.subscribe('transportOver', (foodIndex, count) => {
            if(shop.foodList && shop.foodList.length > 0) {
                this.foodList.children[foodIndex].getChildByName('famous').getComponent(cc.Label).string = '库存:'+ count;
            }
        });
        EventServices.subscribe('addFamous', (num) => {
            shop.famous += num;    
        })
        this.loadingFinish = false;
        this._curLoadIdx = 0;
    },
    update() {
        if(!this.loadingFinish && shop.status == 1){
            this.executePreFrame();
        }
        if(shop.status == 1){
            this.workers.string = `员工：${formatMoney(shop.workers)}/${formatMoney(shop.freeWork)}人`;
            this.income.string = `收入：${formatMoney(shop.income)}元`;
            this.customer.string = `顾客：${(shop.customer)}/${shop.customerList.length}人`;
            this.money.string = `资产：${formatMoney(shop.money)}元`;
            this.koubei.string = `支出：${formatMoney((shop.rent)/30)}元`;
            this.famous.string = `知名度：${formatMoney(shop.famous>10000?10000: shop.famous)}`;
        }
    },
    addWorkers() {
        if(shop.money >= 10000) {
            shop.money -= 10000;
            shop.workers ++;
            shop.freeWork ++;
            shop.rent += 8000;
            show('未来公司','花费了10000元开展招聘会,每个月的支出+8000');
        }else {
            show('劳务派遣','是否委托劳务公司招聘', (res) => {
                if(res) {
                   
                    videoAds.showAd((wd) => {
                        if(wd) {
                            shop.workers ++;
                            shop.freeWork ++;
                            shop.rent += 8000;
                            msg('成功派遣');
                        }
                    })
                }
            })

        }
    },
    reduceWorkers() {
        if(shop.freeWork <= 0) {
            msg('员工正忙，没空搭理你');
            return;
        }
        if(time.day % 30 == 1){
                msg('解雇员工', '解雇成功');
                shop.workers --;
                shop.freeWork --;
                shop.rent -= 8000;
                return ;
        }
        
        show('劳务公司', '是否需要免费解约(合同未到期，每个月一号结算),现在解雇需要支付5000块违约金', (res) => {
            if(res) {
                videoAds.showAd((wd) => {
                    if(wd) {
                        msg('已成功帮你和解员工纠纷');
                        shop.workers --;
                        shop.freeWork --;
                        shop.rent -= 8000;
                    }
                })
            }else {
                shop.money -= 5000;
                shop.workers --;
                shop.freeWork --;
                shop.rent -= 8000;
            }
        })
       
    },
    onDisable(){
        // this.foodList.children.forEach(val=>{
        //     putPrefabPool(val.name, val);
        // })
        this.unscheduleAllCallbacks();
        // this.node.destory();
        this.foodList.destroyAllChildren();
        this.unlockList.destroyAllChildren();
        this.foodList.height = 10;
        this.unlockList.height = 10;
        EventServices.unSubscribe('shopUpdate');
        EventServices.unSubscribe('unlockFood');
        EventServices.unSubscribe('transportOver');
        EventServices.unSubscribe('addFamous');
    },
    showSalePanel () {
        this.node.getChildByName("menuList").active = !this.node.getChildByName("menuList").active;
    },
    //生成店铺信息
    setData (shop) {
        this.shopName.string = shop.shopName;
        this.workers.string = `员工：${shop.workers}/${shop.freeWork}人`;
        this.income.string = `收入：${formatMoney(shop.income)}元`;
        this.customer.string = `顾客：${(shop.customer)}/${shop.customerList.length}人`;
        this.money.string = `资产：${formatMoney(shop.money)}元`;
        this.koubei.string = `支出：${(shop.rent+10000)}元`;
        this.famous.string = `知名度：${formatMoney(shop.famous)}`;
        
        let that = this;
        cc.loader.loadRes(`pic/weather/${shop.weather.weatherId}.png`,cc.SpriteFrame,function(err,spriteFrame){
            that.weatherImg.spriteFrame  = spriteFrame;
        });
        this.weather.string = shop.weather.weatherName;
        msg('今天天气是'+shop.weather.weatherName+ '生意可能会受影响噢')
    },
    //生成商品列表
    setFoodList () {
        console.log("我是严词生成的")
        console.log(this)
        
        shop.menuList.forEach(val=>{
            if(val.state == 1){
                //菜单生成
                let item  = getPrefabPool('food');
                this.foodList.addChild(item);
                item.getChildByName("foodName").getComponent(cc.Label).string = `${val.name}`
                item.getChildByName("sales").getComponent(cc.Label).string = `销量:${formatMoney(val.sales)}`
                item.getChildByName("price").getComponent(cc.Label).string = `价格:${formatMoney(val.price)}`
                item.getChildByName("famous").getComponent(cc.Label).string = `库存:${formatMoney(val.stock)}`
                //合成表
                item.id = val.id;
            }else{
                let item  = getPrefabPool('foodLock');
                this.unlockList.addChild(item);
                item.getChildByName("price").getComponent(cc.Label).string = `知名度：${val.unlockFamous}  花费：${val.unlockMoney}`
            }
        })
    },
    addItem(i) {
        let val = shop.menuList[i];
        if(val.state == 1){
            //菜单生成
            let item  = getPrefabPool('food');
            this.foodList.addChild(item);
            item.getChildByName("foodName").getComponent(cc.Label).string = `${val.name}`
            item.getChildByName("sales").getComponent(cc.Label).string = `销量:${formatMoney(val.sales)}`
            item.getChildByName("price").getComponent(cc.Label).string = `价格:${formatMoney(val.price)}`
            item.getChildByName("famous").getComponent(cc.Label).string = `库存:${formatMoney(val.stock)}`
            item.getChildByName("level").getComponent(cc.Label).string = `${(val.level)}级`
            item.getChildByName("levelCost").getComponent(cc.Label).string = `下级:${formatMoney(val.levelCost)}`;
            //合成表
            item.id = val.id;
            this.foodList.height += 110;
            this.foodList.parent.height += 110;
        }else{
            let item  = getPrefabPool('foodLock');
            this.unlockList.addChild(item);
            item.getChildByName("price").getComponent(cc.Label).string = `知名度：${val.unlockFamous}  花费：${val.unlockMoney}`;
            item.id = val.id;
            this.unlockList.height += 110;
            this.unlockList.parent.height += 110;
        }
    },
    
          // 分帧加载函数
    executePreFrame() {
         let count = 0;
         //一次加载10个
         while(count <= 10){
            count++;
            this.addItem(this._curLoadIdx);
            this._curLoadIdx++;
            if(this._curLoadIdx >= shop.menuList.length ){
                this.loadingFinish = true;
                return ;
            }
         }
    },
    // 可视区域优化
//   calScrollBoxRect() {
//         let scrollView = this.node.getChildByName('menuList').getComponent(cc.ScrollView);
//         let svLeftBottomPoint = scrollView.node.parent.convertToWorldSpaceAR(
//           cc.v2(
//             scrollView.node.x - scrollView.node.anchorX * scrollView.node.width,
//             scrollView.node.y - scrollView.node.anchorY * scrollView.node.height
//           )
//         );
//         console.log(svLeftBottomPoint)
//         // 求出 ScrollView 可视区域在世界坐标系中的矩形（碰撞盒）
//         this.svBBoxRect = cc.rect(
//           svLeftBottomPoint.x,
//           svLeftBottomPoint.y,
//           scrollView.node.width,
//           scrollView.node.height
//         );
//       },
//       handlerScroll() {
//         // 遍历 ScrollView Content 内容节点的子节点
//         let scrollView = this.node.getChildByName('menuList').getComponent(cc.ScrollView);
//         console.log(scrollView.content)
//         scrollView.content.children.forEach((childNode) => {
//           // 对每个子节点的包围盒做和 ScrollView 可视区域包围盒做碰撞判断
//           // 如果相交了，那么就显示，否则就隐藏
//             cc.log(this.svBBoxRect);
//             cc.log(childNode.getBoundingBoxToWorld());
//           if (childNode.getBoundingBoxToWorld().intersects(this.svBBoxRect)) {
//               if (childNode.opacity != 255) {
//                   childNode.emit("on_scroll_view", 255);
//                   // HallEvent.publish('bagScroll',255);
//               }
//           } else {
//               if (childNode.opacity != 0) {
//                   // childNode.opacity = 0;
//                   childNode.emit("on_scroll_view", 0);
//                   // childNode.emit("on_exit_scroll_view", 0);
//                   // HallEvent.publish('bagScroll',0);
//               }
//           }
//         });
//       }
    
});
